﻿using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Goods.Entity;
using NewRetail.Application.Components.Warehouse.Entity;
using NewRetail.Application.Core;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
//add by cl 2022.01.26
namespace NewRetail.Application.Components.Warehouse
{
    public interface IOtherBillService : IApplicationService
    {
        Task<OtherBill[]> AttachWarehouse(OtherBill[] data);
        Task<OtherBill[]> AttachGoodsInfo(OtherBill[] data);
    }

    public class OtherBillService : MyApplicationService, IOtherBillService
    {
        private readonly IRepository<OtherBill> otherBills;
        public OtherBillService(IRepository<OtherBill> otherBills)
        {
            this.otherBills = otherBills;
        }

        public async Task<OtherBill[]> AttachWarehouse(OtherBill[] data)
        {
            var db = await this.otherBills.GetDbContextAsync();

            await db.AttachData<Warehouse.Entity.Warehouse, OtherBill>(
                data, idGetter: x => x.warehouseID, action: (m, arr) =>
                {
                    m.Warehouse = arr.FirstOrDefault();
                });

            return data;
        }
        public async Task<OtherBill[]> AttachGoodsInfo(OtherBill[] data)
        {
            var db = await this.otherBills.GetDbContextAsync();

            await db.AttachData<GoodsInfo, OtherBill>(data, x => x.goodsID, (m, arr) =>
            {
                m.GoodsInfo = arr.FirstOrDefault();
            });

            //添加成本价
            var ids = data.Select(x => x.goodsID).ToArray();
            var goodsPrices = await db.Set<WarehouseGoods>().Where(x => ids.Contains(x.goodsID)).ToArrayAsync();
            foreach (var item in data)
            {
                item.GoodsInfo.GoodsPrices = goodsPrices.Where(x => x.goodsID == item.goodsID && x.warehouseID == item.warehouseID).ToArray();
            }

            return data;
        }
    }
}
